#include "widget.h"
#include "net_access_audit_manager.h"

#include <QFormLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QSpinBox>
#include <QTextBrowser>
#include <QVBoxLayout>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , m_auditManager(new NetAccessAuditManager())
{
    QVBoxLayout *verticalLayout = new QVBoxLayout;
    QHBoxLayout *horizontalLayout = new QHBoxLayout;
    QFormLayout *formLayout = new QFormLayout;

    QLabel *ips = new QLabel("ips:", this);
    m_ips = new QLineEdit(this);
    formLayout->setWidget(0, QFormLayout::LabelRole, ips);
    formLayout->setWidget(0, QFormLayout::FieldRole, m_ips);

    QLabel *ports = new QLabel("ports:", this);
    m_ports = new QLineEdit(this);
    formLayout->setWidget(1, QFormLayout::LabelRole, ports);
    formLayout->setWidget(1, QFormLayout::FieldRole, m_ports);

    QLabel *times = new QLabel("去重时间间隔(S):", this);
    m_timesBox = new QSpinBox(this);
    m_timesBox->setMinimum(1);
    m_timesBox->setValue(1);
    formLayout->setWidget(2, QFormLayout::LabelRole, times);
    formLayout->setWidget(2, QFormLayout::FieldRole, m_timesBox);

    horizontalLayout->addLayout(formLayout);

    QPushButton *pushButton = new QPushButton("刷新", this);
    connect(pushButton, &QPushButton::clicked, this, [&]() {
        extern int g_timeSpaces;
        g_timeSpaces = m_timesBox->value();
        m_auditManager->refresh(m_ips->text().split(","), m_ports->text().split(","));
    });
    horizontalLayout->addWidget(pushButton);

    verticalLayout->addLayout(horizontalLayout);

    m_display = new QTextBrowser(this);

    verticalLayout->addWidget(m_display);

    pushButton = new QPushButton("清理", this);
    connect(pushButton, &QPushButton::clicked, m_display, &QTextBrowser::clear);
    verticalLayout->addWidget(pushButton);
    setLayout(verticalLayout);

    connect(m_auditManager, &NetAccessAuditManager::accessNotify, this, [&](const QString &ip, int port) {
        m_display->insertPlainText(ip + ":" + QString::number(port) + "\r\n");
    });
}